package com.appspot.didit.test.service;

import javax.jdo.PersistenceManager;

import com.appspot.didit.client.user.User;
import com.appspot.didit.server.UserServiceImpl;
import com.appspot.didit.server.PMF;
import com.appspot.didit.server.UtilServer;
import com.appspot.didit.test.LocalServiceTestCase;

public class UserServiceTestCase extends LocalServiceTestCase {

	private UserServiceImpl usi = new UserServiceImpl();
	PersistenceManager pm = PMF.get().getPersistenceManager();
	
	public void testNewUser() {
	    try {
	    	String username = "xinyan.lei";
			String password = "123456";
	    	User u1 = usi.newUser(username, password); 
		    User u2 = pm.getObjectById(User.class, u1.getId());
		    assertEquals("xinyan.lei", u2.getUsername());
			assertEquals("123456", u2.getPassword());
	    } catch (Exception e) {
	    	System.out.println(e.toString());
	    	assertTrue(false);
	    } finally {
	      pm.close();
	    }
	}
	
	public void testIsAvailable() {
	    try {
	    	String username = "xinyan.lei";
			String password = "123456";
		    User u = new User(username, password);
	    	pm.makePersistent(u);
		    assertFalse(usi.isAvailable(username));
		    assertTrue(usi.isAvailable("xinyanlei"));
	    } catch (Exception e) {
	    	System.out.println(e.toString());
	    	assertTrue(false);
	    } finally {
	      pm.close();
	    }
	}

	public void testAuthenticate() {
		try {
	    	String username = "xinyan.lei";
			String password = "123456";
		    User uh = new User(username, password);
	    	pm.makePersistent(uh);
	    	String fakeUsername = "xinyanlei";
	    	User user = usi.authenticate(username, password);
		    assertNotNull(user);
		    assertEquals(username, user.getUsername());
		    assertEquals(user.getPassword(), password);
		    user = usi.authenticate(fakeUsername, password);
		    assertNull(user);
	    } catch (Exception e) {
	    	System.out.println(e.toString());
	    	assertTrue(false);
	    } finally {
	      pm.close();
	    }
	}
	
}
